{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "# Text classification from scratch\n",
    "\n",
    "**Authors:** Mark Omernick, Francois Chollet<br>\n",
    "**Date created:** 2019/11/06<br>\n",
    "**Last modified:** 2020/05/17<br>\n",
    "**Description:** Text sentiment classification starting from raw text files."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Introduction\n",
    "\n",
    "This example shows how to do text classification starting from raw text (as\n",
    "a set of text files on disk). We demonstrate the workflow on the IMDB sentiment\n",
    "classification dataset (unprocessed version). We use the `TextVectorization` layer for\n",
    " word splitting & indexing.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Setup\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Load the data: IMDB movie review sentiment classification\n",
    "\n",
    "Let's download the data and inspect its structure.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "!curl -O https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n",
    "!tar -xf aclImdb_v1.tar.gz\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "The `aclImdb` folder contains a `train` and `test` subfolder:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "!ls aclImdb\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "!ls aclImdb/test\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "!ls aclImdb/train\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "The `aclImdb/train/pos` and `aclImdb/train/neg` folders contain text files, each of\n",
    " which represents on review (either positive or negative):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "!cat aclImdb/train/pos/6248_7.txt\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "We are only interest in the `pos` and `neg` subfolders, so let's delete the rest:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "!rm -r aclImdb/train/unsup\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "You can use the utility `tf.keras.preprocessing.text_dataset_from_directory` to\n",
    "generate a labeled `tf.data.Dataset` object from a set of text files on disk filed\n",
    " into class-specific folders.\n",
    "\n",
    "Let's use it to generate the training, validation, and test datasets. The validation\n",
    "and training datasets are generated from two subsets of the `train` directory, with 20%\n",
    "of samples going to the validation dataset and 80% going to the training dataset.\n",
    "\n",
    "Having a validation dataset in addition to the test dataset is useful for tuning\n",
    "hyperparameters, such as the model architecture, for which the test dataset should not\n",
    "be used.\n",
    "\n",
    "Before putting the model out into the real world however, it should be retrained using all\n",
    "available training data (without creating a validation dataset), so its performance is maximized.\n",
    "\n",
    "When using the `validation_split` & `subset` arguments, make sure to either specify a\n",
    "random seed, or to pass `shuffle=False`, so that the validation & training splits you\n",
    "get have no overlap.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "batch_size = 32\n",
    "raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory(\n",
    "    \"aclImdb/train\",\n",
    "    batch_size=batch_size,\n",
    "    validation_split=0.2,\n",
    "    subset=\"training\",\n",
    "    seed=1337,\n",
    ")\n",
    "raw_val_ds = tf.keras.preprocessing.text_dataset_from_directory(\n",
    "    \"aclImdb/train\",\n",
    "    batch_size=batch_size,\n",
    "    validation_split=0.2,\n",
    "    subset=\"validation\",\n",
    "    seed=1337,\n",
    ")\n",
    "raw_test_ds = tf.keras.preprocessing.text_dataset_from_directory(\n",
    "    \"aclImdb/test\", batch_size=batch_size\n",
    ")\n",
    "\n",
    "print(\n",
    "    \"Number of batches in raw_train_ds: %d\"\n",
    "    % tf.data.experimental.cardinality(raw_train_ds)\n",
    ")\n",
    "print(\n",
    "    \"Number of batches in raw_val_ds: %d\" % tf.data.experimental.cardinality(raw_val_ds)\n",
    ")\n",
    "print(\n",
    "    \"Number of batches in raw_test_ds: %d\"\n",
    "    % tf.data.experimental.cardinality(raw_test_ds)\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Let's preview a few samples:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# It's important to take a look at your raw data to ensure your normalization\n",
    "# and tokenization will work as expected. We can do that by taking a few\n",
    "# examples from the training set and looking at them.\n",
    "# This is one of the places where eager execution shines:\n",
    "# we can just evaluate these tensors using .numpy()\n",
    "# instead of needing to evaluate them in a Session/Graph context.\n",
    "for text_batch, label_batch in raw_train_ds.take(1):\n",
    "    for i in range(5):\n",
    "        print(text_batch.numpy()[i])\n",
    "        print(label_batch.numpy()[i])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Prepare the data\n",
    "\n",
    "In particular, we remove `<br />` tags.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.layers.experimental.preprocessing import TextVectorization\n",
    "import string\n",
    "import re\n",
    "\n",
    "# Having looked at our data above, we see that the raw text contains HTML break\n",
    "# tags of the form '<br />'. These tags will not be removed by the default\n",
    "# standardizer (which doesn't strip HTML). Because of this, we will need to\n",
    "# create a custom standardization function.\n",
    "def custom_standardization(input_data):\n",
    "    lowercase = tf.strings.lower(input_data)\n",
    "    stripped_html = tf.strings.regex_replace(lowercase, \"<br />\", \" \")\n",
    "    return tf.strings.regex_replace(\n",
    "        stripped_html, \"[%s]\" % re.escape(string.punctuation), \"\"\n",
    "    )\n",
    "\n",
    "\n",
    "# Model constants.\n",
    "max_features = 20000\n",
    "embedding_dim = 128\n",
    "sequence_length = 500\n",
    "\n",
    "# Now that we have our custom standardization, we can instantiate our text\n",
    "# vectorization layer. We are using this layer to normalize, split, and map\n",
    "# strings to integers, so we set our 'output_mode' to 'int'.\n",
    "# Note that we're using the default split function,\n",
    "# and the custom standardization defined above.\n",
    "# We also set an explicit maximum sequence length, since the CNNs later in our\n",
    "# model won't support ragged sequences.\n",
    "vectorize_layer = TextVectorization(\n",
    "    standardize=custom_standardization,\n",
    "    max_tokens=max_features,\n",
    "    output_mode=\"int\",\n",
    "    output_sequence_length=sequence_length,\n",
    ")\n",
    "\n",
    "# Now that the vocab layer has been created, call `adapt` on a text-only\n",
    "# dataset to create the vocabulary. You don't have to batch, but for very large\n",
    "# datasets this means you're not keeping spare copies of the dataset in memory.\n",
    "\n",
    "# Let's make a text-only dataset (no labels):\n",
    "text_ds = raw_train_ds.map(lambda x, y: x)\n",
    "# Let's call `adapt`:\n",
    "vectorize_layer.adapt(text_ds)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Two options to vectorize the data\n",
    "\n",
    "There are 2 ways we can use our text vectorization layer:\n",
    "\n",
    "**Option 1: Make it part of the model**, so as to obtain a model that processes raw\n",
    " strings, like this:\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "```python\n",
    "text_input = tf.keras.Input(shape=(1,), dtype=tf.string, name='text')\n",
    "x = vectorize_layer(text_input)\n",
    "x = layers.Embedding(max_features + 1, embedding_dim)(x)\n",
    "...\n",
    "```\n",
    "\n",
    "**Option 2: Apply it to the text dataset** to obtain a dataset of word indices, then\n",
    " feed it into a model that expects integer sequences as inputs.\n",
    "\n",
    "An important difference between the two is that option 2 enables you to do\n",
    "**asynchronous CPU processing and buffering** of your data when training on GPU.\n",
    "So if you're training the model on GPU, you probably want to go with this option to get\n",
    " the best performance. This is what we will do below.\n",
    "\n",
    "If we were to export our model to production, we'd ship a model that accepts raw\n",
    "strings as input, like in the code snippet for option 1 above. This can be done after\n",
    " training. We do this in the last section.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "\n",
    "def vectorize_text(text, label):\n",
    "    text = tf.expand_dims(text, -1)\n",
    "    return vectorize_layer(text), label\n",
    "\n",
    "\n",
    "# Vectorize the data.\n",
    "train_ds = raw_train_ds.map(vectorize_text)\n",
    "val_ds = raw_val_ds.map(vectorize_text)\n",
    "test_ds = raw_test_ds.map(vectorize_text)\n",
    "\n",
    "# Do async prefetching / buffering of the data for best performance on GPU.\n",
    "train_ds = train_ds.cache().prefetch(buffer_size=10)\n",
    "val_ds = val_ds.cache().prefetch(buffer_size=10)\n",
    "test_ds = test_ds.cache().prefetch(buffer_size=10)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Build a model\n",
    "\n",
    "We choose a simple 1D convnet starting with an `Embedding` layer.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras import layers\n",
    "\n",
    "# A integer input for vocab indices.\n",
    "inputs = tf.keras.Input(shape=(None,), dtype=\"int64\")\n",
    "\n",
    "# Next, we add a layer to map those vocab indices into a space of dimensionality\n",
    "# 'embedding_dim'.\n",
    "x = layers.Embedding(max_features, embedding_dim)(inputs)\n",
    "x = layers.Dropout(0.5)(x)\n",
    "\n",
    "# Conv1D + global max pooling\n",
    "x = layers.Conv1D(128, 7, padding=\"valid\", activation=\"relu\", strides=3)(x)\n",
    "x = layers.Conv1D(128, 7, padding=\"valid\", activation=\"relu\", strides=3)(x)\n",
    "x = layers.GlobalMaxPooling1D()(x)\n",
    "\n",
    "# We add a vanilla hidden layer:\n",
    "x = layers.Dense(128, activation=\"relu\")(x)\n",
    "x = layers.Dropout(0.5)(x)\n",
    "\n",
    "# We project onto a single unit output layer, and squash it with a sigmoid:\n",
    "predictions = layers.Dense(1, activation=\"sigmoid\", name=\"predictions\")(x)\n",
    "\n",
    "model = tf.keras.Model(inputs, predictions)\n",
    "\n",
    "# Compile the model with binary crossentropy loss and an adam optimizer.\n",
    "model.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Train the model\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "epochs = 3\n",
    "\n",
    "# Fit the model using the train and test datasets.\n",
    "model.fit(train_ds, validation_data=val_ds, epochs=epochs)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Evaluate the model on the test set\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "model.evaluate(test_ds)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Make an end-to-end model\n",
    "\n",
    "If you want to obtain a model capable of processing raw strings, you can simply\n",
    "create a new model (using the weights we just trained):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# A string input\n",
    "inputs = tf.keras.Input(shape=(1,), dtype=\"string\")\n",
    "# Turn strings into vocab indices\n",
    "indices = vectorize_layer(inputs)\n",
    "# Turn vocab indices into predictions\n",
    "outputs = model(indices)\n",
    "\n",
    "# Our end to end model\n",
    "end_to_end_model = tf.keras.Model(inputs, outputs)\n",
    "end_to_end_model.compile(\n",
    "    loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"]\n",
    ")\n",
    "\n",
    "# Test it with `raw_test_ds`, which yields raw strings\n",
    "end_to_end_model.evaluate(raw_test_ds)\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "text_classification_from_scratch",
   "private_outputs": false,
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}